package com.example.dine.call.view.impl;

import com.example.dine.call.entity.DiningTable;
import com.example.dine.call.entity.Queue;
import com.example.dine.call.mapper.DiningTableMapper;
import com.example.dine.call.mapper.QueueMapper;
import com.example.dine.call.util.QRCodeUtils;
import com.example.dine.call.view.IDineCallView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;

/**
 * DineCallViewImpl类，实现了IDineCallView接口，提供了DineCall系统的视图组件。
 */
@Component
public class DineCallViewImpl implements IDineCallView {

    @Autowired
    private DiningTableMapper diningTableMapper;

    @Autowired
    private QueueMapper queueMapper;

    private Scanner scanner = new Scanner(System.in);

    @Override
    public int displayMainMenu() {
        System.out.println("欢迎使用DineCall排队叫号系统，请选择您的操作：");
        System.out.println("1. 【顾客】取号");
        System.out.println("2. 【顾客】查询排队信息");
        System.out.println("3. 【顾客】应答叫号");
        System.out.println("4. 【餐厅】叫号");
        System.out.println("5. 【餐厅】查看排队列表");
        System.out.println("6. 【餐厅】查看已叫号列表");
        System.out.println("7. 【餐厅】查看餐桌列表");
        System.out.println("8. 【餐厅】增加餐桌");
        System.out.println("9. 【餐厅】删除餐桌");
        System.out.println("10. 【调试】解析二维码");
        System.out.println("0. 【系统】退出系统");
        int choice = Integer.parseInt(input(LABEL_INPUT_OPERATION_NUMBER, REGEX_OPERATION_NUMBER, false));
        System.out.println(); // 添加空白行
        return choice;
    }

    @Override
    public void customerQueue() {
        System.out.println("【系统】顾客取号");
        String partySizeInput = input(LABEL_INPUT_PARTY_SIZE, REGEX_PARTY_SIZE, false);
        int partySize = Integer.parseInt(partySizeInput);
        String typeCode = "";
        if (partySize <= 2) {
            typeCode = "A";
        } else if (partySize <= 4) {
            typeCode = "B";
        } else if (partySize <= 8) {
            typeCode = "C";
        }
        int queueNumber = queueMapper.countByDate(LocalDate.now()) + 1;
        Queue queue = new Queue();
        queue.setPartySize(partySize);
        queue.setTypeCode(typeCode);
        queue.setQueueNumber(queueNumber);
        queue.setStatus(0);
        queue.setCreatedAt(LocalDateTime.now());

        List<DiningTable> diningTables = diningTableMapper.list();
        DiningTable availableTable = null;
        for (DiningTable table : diningTables) {
            if (table.getTypeCode().equals(typeCode) && table.getStatus() == 0) {
                availableTable = table;
                break;
            }
        }

        if (availableTable != null) {
            queue.setStatus(1);
            diningTableMapper.updateStatusById(availableTable.getId(), 1);
        }

        queueMapper.insert(queue);

        if (queue.getStatus() == 0) {
            System.out.println("【系统】取号成功，您的排队号码是：" + queue.getTypeCode() + queue.getQueueNumber());
        } else {
            System.out.println("【系统】取号成功，当前有合适的空闲餐桌，请直接就餐");
        }

        // 调试信息输出
        System.out.println("【调试】取号信息：" + queue);

        // 生成二维码
        String path = QRCodeUtils.generate(queue);
        System.out.println("【调试】排队二维码图片：" + path);
    }

    @Override
    public void customerQueryQueue() {
        System.out.println("【系统】顾客查询排队信息");
        String queueNumberInput = input(LABEL_INPUT_QUEUE_NUMBER, REGEX_QUEUE_NUMBER, false);
        char typeCodeChar = queueNumberInput.charAt(0);
        String queueNumberStr = queueNumberInput.substring(1);
        int queueNumber = Integer.parseInt(queueNumberStr);
        String typeCode = String.valueOf(typeCodeChar);
        List<Queue> queues = queueMapper.listByDate(LocalDate.now());
        List<Queue> filteredQueues = new ArrayList<>();
        for (Queue queue : queues) {
            if (queue.getStatus() != 1 && queue.getTypeCode().equals(typeCode)) {
                filteredQueues.add(queue);
            }
        }
        filteredQueues.sort(Comparator.comparing(Queue::getCreatedAt));
        for (int i = 0; i < filteredQueues.size(); i++) {
            Queue queue = filteredQueues.get(i);
            if (queue.getQueueNumber() == queueNumber) {
                System.out.println("【系统】您前面还有" + i + "位顾客");
                return;
            }
        }
        System.out.println("【错误】您的排队号码不存在");
    }

    @Override
    public void customerResponse() {
        System.out.println("【系统】开始处理顾客应答");
        String queueNumberInput = input(LABEL_INPUT_QUEUE_NUMBER, REGEX_QUEUE_NUMBER, false);
        char typeCodeChar = queueNumberInput.charAt(0);
        String queueNumberStr = queueNumberInput.substring(1);
        int queueNumber = Integer.parseInt(queueNumberStr);
        String typeCode = String.valueOf(typeCodeChar);
        List<Queue> queues = queueMapper.listByDate(LocalDate.now());
        Queue matchedQueue = null;
        for (Queue queue : queues) {
            if (queue.getTypeCode().equals(typeCode) && queue.getQueueNumber() == queueNumber) {
                matchedQueue = queue;
                break;
            }
        }
        if (matchedQueue == null) {
            System.out.println("【错误】排队号码不存在");
        } else {
            queueMapper.updateStatusById(matchedQueue.getId(), 1);
            List<DiningTable> diningTables = diningTableMapper.list();
            DiningTable availableTable = null;
            for (DiningTable table : diningTables) {
                if (table.getTypeCode().equals(typeCode) && table.getStatus() == 0) {
                    availableTable = table;
                    break;
                }
            }
            if (availableTable != null) {
                diningTableMapper.updateStatusById(availableTable.getId(), 1);
                System.out.println("【系统】应答成功，请顾客前往" + availableTable.getId() + "就餐");
            }
        }
    }

    @Override
    public void restaurantCall() {
        System.out.println("【系统】开始处理餐厅 叫号");
        String tableIdInput = input(LABEL_INPUT_TABLE_ID, REGEX_TABLE_ID, false);
        Long tableId = Long.parseLong(tableIdInput);
        DiningTable diningTable = diningTableMapper.selectById(tableId);
        if (diningTable == null) {
            System.out.println("【错误：输入的餐桌号错误】");
        } else {
            diningTableMapper.updateStatusById(tableId, 0);
            String typeCode = diningTable.getTypeCode();
            List<Queue> queues = queueMapper.listByDate(LocalDate.now());
            Queue matchedQueue = null;
            for (Queue queue : queues) {
                if (queue.getTypeCode().equals(typeCode) && queue.getStatus() == 0) {
                    matchedQueue = queue;
                    break;
                }
            }
            if (matchedQueue != null) {
                System.out.println("【系统】请" + matchedQueue.getTypeCode() + matchedQueue.getQueueNumber() + "顾客准备就餐");
            } else {
                System.out.println("【系统】当前没有需要" + diningTable.getCapacity() + "人桌且正在排队的顾客");
            }
        }
    }

    @Override
    public void viewQueueList() {
        System.out.println("【系统】开始查询排队列表");
        List<Queue> queues = queueMapper.listByDate(LocalDate.now());
        for (Queue queue : queues) {
            if (queue.getStatus() == 0) {
                System.out.println(queue.showInfo());
            }
        }
        System.out.println("【系统】查询排队列表，结束");
    }

    @Override
    public void viewCalledQueueList() {
        System.out.println("【系统】开始查询已叫号列表");
        List<Queue> queues = queueMapper.listByDate(LocalDate.now());
        for (Queue queue : queues) {
            if (queue.getStatus() == 1) {
                System.out.println(queue.showInfo());
            }
        }
        System.out.println("【系统】查询已叫号列表，结束");
    }

    @Override
    public void viewTableList() {
        System.out.println("【系统】开始查看餐桌列表");
        List<DiningTable> diningTables = diningTableMapper.list();
        for (DiningTable table : diningTables) {
            System.out.println(table.showInfo());
        }
        System.out.println("【系统】查看餐桌列表，结束");
    }

    @Override
    public void addTable() {
        System.out.println("【系统】开始增加餐桌");
        String capacityInput = input(LABEL_INPUT_CAPACITY, REGEX_CAPACITY, false);
        int capacity = Integer.parseInt(capacityInput);
        String typeCode = "";
        if (capacity == 2) {
            typeCode = "A";
        } else if (capacity == 4) {
            typeCode = "B";
        } else if (capacity == 8) {
            typeCode = "C";
        }
        DiningTable diningTable = new DiningTable();
        diningTable.setCapacity(capacity);
        diningTable.setTypeCode(typeCode);
        diningTable.setStatus(0);
        diningTableMapper.insert(diningTable);
        System.out.println("【系统】增加餐桌，结束");
    }

    @Override
    public void deleteTable() {
        System.out.println("【系统】删除餐桌");
        String tableIdInput = input(LABEL_INPUT_TABLE_ID, REGEX_TABLE_ID, false);
        Long tableId = Long.parseLong(tableIdInput);
        DiningTable diningTable = diningTableMapper.selectById(tableId);
        if (diningTable == null) {
            System.out.println("【错误：尝试删除的数据不存在】");
        } else {
            diningTableMapper.deleteById(tableId);
            System.out.println("【系统】删除餐桌，结束");
        }
    }

    @Override
    public void parseQRCode() {
        System.out.println("【系统】开始解析二维码");
        String filePath = input(LABEL_INPUT_QR_CODE_PATH, REGEX_QR_CODE_PATH, false);
        Queue queue = QRCodeUtils.parse(filePath);
        if (queue != null) {
            System.out.println(queue.showInfo());
        } else {
            System.out.println("【错误】解析二维码失败");
        }
    }

    @Override
    public void exitSystem() {
        System.out.println("【系统】感谢使用，再见！");
        System.exit(0);
    }

    /**
     * 获取用户输入。
     *
     * @param prompt     提示文本。
     * @param regex      正则表达式。
     * @param allowEmpty 是否允许为空。
     * @return 用户输入的值。
     */
    private String input(String prompt, String regex, boolean allowEmpty) {
        while (true) {
            System.out.print(prompt);
            String input = scanner.nextLine();
            if (input.equalsIgnoreCase("/exit")) {
                exitSystem();
            }
            if (allowEmpty && input.isEmpty()) {
                return null;
            }
            if (input.matches(regex)) {
                return input;
            }
            System.out.println("【错误】您输入的格式有误，请重新输入");
        }
    }
}